import re


RE_BOOK_XML_CHAPTER_PAT = r'\s*<xi:include\s+xmlns:xi="http://www.w3.org/2001/XInclude"\s+href="%s"\s*/>'

RE_PARA_BREAK = re.compile(r'\s*\n\s*\n[\s\n]*')

# DocBook block elements are protected from having <para> tags
# inserted automatically. Note that this simplified parsing logic
# requires that the elements listed here not be nestable (so <section>
# doesn't work here).
DOCBOOK_BLOCK_ELEMENTS = (
    'address',
    'blockquote',
    'calloutlist',
    'caution',
    'cmdsynopsis',
    'epigraph',
    'equation',
    'example',
    'figure',
    'formalpara',
    'funcsymbols',
    'glosslist',
    'graphic',
    'highlights',
    'important',
    'informalequation',
    'informalexample',
    'informalfigure',
    'informaltable',
    'informaltable',
    'itemizedlist',
    'literallayout',
    'mediaobject',
    'msgset',
    'note',
    'orderedlist',
    'procedure',
    'programlisting',
    'qandaset',
    'screen',
    'screenshot',
    'segmentedlist',
    'sidebar',
    'simpara',
    'simplelist',
    'synopsis',
    'table',
    'tip',
    'variablelist',
    'variablelist',
    'warning',
    )
DOCBOOK_BLOCK_ELEMENT_PATTERN = '|'.join(DOCBOOK_BLOCK_ELEMENTS)
RE_BLOCK_ELEM = re.compile(
    r'(<(%s) ?[^>]*>.*?</\2>)' %
    DOCBOOK_BLOCK_ELEMENT_PATTERN,
    # TODO: This is a bug when elements nest, which happens when a figure contains a mediaobject, or an example comtains a programlisting.  Closing tag must match opening tag; grouping messes up the splits.
    re.DOTALL)


# TODO: For future reference, the DocBook tags that require literal
# layout are: 'address', 'literallayout', 'programlisting', 'screen',
# 'screenshot', 'synopsis'


class Section(object):
    def __init__(self, id, title, text, parent=None):
        self.title = title
        self.text = text
        self.parent = parent
        self.inner_sections = []
        self.section_id = id

    def add_section(self, section):
        self.inner_sections.append(section)
        section.parent = self

    def __iter__(self):
        for section in self.inner_sections:
            yield section


class Document(object):
    """Compiles a document from one or more OPML files.

    doc = Document()
    for filename in filenames:
        fh = open(filename)
        doc.parse_opml(fh.read())
        fh.close()
    """
    def __init__(self):
        self.top_sections = []
